package com.web.server.util;

import java.util.Base64;
import java.util.Locale;
import java.util.UUID;

public final class Util {
	private Util() {}

//	public static String b64Encode(byte[] content) {

//		return Base64.getEncoder().encodeToString(content);
//	}

	public static String b64Decode(String content) {
		return toHexString(Base64.getDecoder().decode(content));
	}

	public static String getUUID() {
		return UUID.randomUUID().toString().toLowerCase();
	}

	public static byte[] toByteArray(String hexStr) {
		try {
			String hexString = hexStr.replace(" ", "");
			if (hexString.length() % 2 == 0) {
				int    len       = hexString.length() / 2;
				byte[] byteArray = new byte[len];
				int    index     = 0;
				for (int i = 0; i < len; i++) {
					byteArray[i] = (byte) Integer.parseInt(hexString.substring(index, index + 2), 16);
					index += 2;
				}
				return byteArray;
			}
			throw new RuntimeException("Error Hex length.");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String toHexString(byte[] buffer) {
		return toHexString(buffer, 0);
	}

	public static String toHexString(byte[] buffer, int offset) {
		StringBuilder res = new StringBuilder();
		for (int i = offset; i < buffer.length; i++) {
			res.append(byteToHex(buffer[i]));
		}
		return res.toString();
	}

	public static String byteToHex(byte byteValue) {
		String hexString = Integer.toHexString(byteValue & 0xFF);
		boolean b = hexString.length() < 2;
		if (b) {
			hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
		}
		return hexString.toUpperCase(Locale.getDefault());
	}
}
